package com.example.wzjsign.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.input.DialogInputExtKt;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.wzjsign.R;
import com.example.wzjsign.global.Constants;
import com.example.wzjsign.global.SpKey;
import com.example.wzjsign.widget.WebLayout;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.IUrlLoader;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.tv_sign_address)
    TextView tvSignAddress;
    @BindView(R.id.tv_sign_interval)
    TextView tvSignInterval;
    @BindView(R.id.ll_webView)
    LinearLayout llWebView;
    private AgentWeb mAgentWeb;
    private String mSignAddress;
    private int mSignInterval;
    private ThreadUtils.Task<String> mSignTask;
    private boolean mIsSign;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();

    }

    //初始化视图
    private void initView() {
        mSignAddress = SPUtils.getInstance().getString(SpKey.SIGN_ADDRESS, Constants.BAI_DU_ADDRESS);
        mSignInterval = SPUtils.getInstance().getInt(SpKey.SIGN_INTERVAL, Constants.DEFAULT_SIGN_INTERVAL);
        tvSignAddress.setText(mSignAddress);
        tvSignInterval.setText(mSignInterval + "s");
        mIsSign = false;
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(llWebView, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setWebLayout(new WebLayout(this))
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                .createAgentWeb()
                .ready()
                .go(mSignAddress);
    }

    private com.just.agentweb.WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            /*if (mTitleTextView != null) {
                mTitleTextView.setText(title);
            }*/
        }
    };

    private com.just.agentweb.WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted");
        }
    };


    @OnClick({R.id.btn_update_sign_address, R.id.btn_test_sign_address, R.id.btn_start_sign, R.id.btn_end_sign, R.id.btn_update_sign_interval})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_update_sign_address:
                updateSignAddress();
                break;
            case R.id.btn_test_sign_address:
                testSignAddress();
                break;
            case R.id.btn_start_sign:
                startSign();
                break;
            case R.id.btn_end_sign:
                endSign();
                break;
            case R.id.btn_update_sign_interval:
                updateSignInterval();
                break;
        }
    }


    private void updateSignInterval() {
        MaterialDialog dialog = new MaterialDialog(this, MaterialDialog.getDEFAULT_BEHAVIOR());
        dialog.title(null, "修改签到间隔(秒)");
        DialogInputExtKt.input(dialog, "请输入签到间隔(秒)", null, null, null,
                InputType.TYPE_CLASS_TEXT,
                null, true, false, (materialDialog, text) -> {

                    SPUtils.getInstance().put(SpKey.SIGN_INTERVAL, Integer.parseInt(text.toString()));
                    mSignInterval = Integer.parseInt(text.toString());
                    tvSignInterval.setText(mSignInterval + "s");
                    dialog.dismiss();
                    return null;
                });
        DialogInputExtKt.getInputField(dialog).setText(mSignInterval + "");
        dialog.setAutoDismissEnabled$com_afollestad_material_dialogs_core(false);
        dialog.positiveButton(null, "确定", materialDialog -> {

            return null;
        });
        dialog.negativeButton(null, "取消", materialDialog -> {
            dialog.dismiss();
            return null;
        });
        dialog.show();
    }

    private void updateSignAddress() {
        MaterialDialog dialog = new MaterialDialog(this, MaterialDialog.getDEFAULT_BEHAVIOR());
        dialog.title(null, "修改签到地址");
        DialogInputExtKt.input(dialog, "请输入签到地址", null, null, null,
                InputType.TYPE_CLASS_TEXT,
                null, true, false, (materialDialog, text) -> {

                    SPUtils.getInstance().put(SpKey.SIGN_ADDRESS, text.toString());
                    mSignAddress = text.toString();
                    tvSignAddress.setText(mSignAddress);
                    dialog.dismiss();
                    return null;
                });
        DialogInputExtKt.getInputField(dialog).setText(mSignAddress);
        dialog.setAutoDismissEnabled$com_afollestad_material_dialogs_core(false);
        dialog.positiveButton(null, "确定", materialDialog -> {

            return null;
        });
        dialog.negativeButton(null, "取消", materialDialog -> {
            dialog.dismiss();
            return null;
        });
        dialog.show();

    }

    private void testSignAddress() {
        mAgentWeb.getUrlLoader().loadUrl(mSignAddress);

    }


    private void startSign() {
        if (!mIsSign) {
            mSignTask = new ThreadUtils.Task<String>() {
                @Override
                public String doInBackground() throws Throwable {
                    return null;
                }

                @Override
                public void onSuccess(String result) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAgentWeb.getUrlLoader().loadUrl(mSignAddress);
                        }
                    });


                }

                @Override
                public void onCancel() {

                }

                @Override
                public void onFail(Throwable t) {

                }
            };

            ThreadUtils.executeByCachedAtFixRate(mSignTask, Long.parseLong(mSignInterval + ""), TimeUnit.SECONDS);
            mIsSign = true;
        } else {
            ToastUtils.showShort("已经开始签到了");
        }
    }

    private void endSign() {
        ThreadUtils.cancel(mSignTask);
        mIsSign = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        endSign();
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > Constants.EXIT_TIME) {
            ToastUtils.showShort("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_doc:
                showDoc();
                break;
            case R.id.action_version:
                showVersion();
                break;
        }

        return super.onOptionsItemSelected(item);
    }


    private void showDoc() {
        MaterialDialog dialog = new MaterialDialog(this, MaterialDialog.getDEFAULT_BEHAVIOR());
        dialog.title(null, "说明");
        String doc =
                "1.从微信进入微助教签到页,获得签到页面地址,如:https://v18.teachermate.cn/wechat-pro-ssr/student/sign?openid=6fb87441b1fa105ed4b7d0e29750d659。"
                        + "\n"
                        + "2.进入此程序设置签到地址与签到间隔，开始签到。" + "\n"
                        + "注：如果之后再次进入微助教openId会发生变化请重新设置签到地址，可通过点击查看历史签到来测试是否是可用的签到地址。";
        dialog.message(null, doc, null);
        dialog.positiveButton(null, "确定", materialDialog -> {

            return null;
        });

        dialog.show();
    }

    private void showVersion() {
        MaterialDialog dialog = new MaterialDialog(this, MaterialDialog.getDEFAULT_BEHAVIOR());
        dialog.title(null, "版本");

        dialog.message(null, "版本号：" + AppUtils.getAppVersionName(), null);
        dialog.positiveButton(null, "确定", materialDialog -> {

            return null;
        });

        dialog.show();
    }
}